<script lang='ts' setup>
import { reactive, defineAsyncComponent, ref, computed} from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { api as ViewerApi } from 'v-viewer'
import folderAdd from '/@/assets/svg/folderAdd.svg?url';
import folder from '/@/assets/svg/folder.svg?url';
import { dirList, fileList, dirDelete, fileUpload,fileMove,fileDelete,fileBatchDelete } from '/@/api/commodity';
const xgPlayVideo = defineAsyncComponent(() => import('/@/components/information/xgPlayVideo.vue'))
const AddDirTree = defineAsyncComponent(() => import('/@/components/information/AddCategoryTree.vue'))
const UploadVideo = defineAsyncComponent(() => import('/@/components/information/UploadVideo.vue'))
const UploadImage = defineAsyncComponent(() => import('/@/components/information/UploadImage.vue'))

const xgPlayVideoRef = ref();
const addDirTreeRef = ref();
const uploadImageRef = ref();
const uploadVideoRef = ref();

const emit = defineEmits(['selectFun'])

export interface Tree {
    id: number
    label: string
    pid: number
    children?: Tree[]
    value?: number,
}

const state = reactive({
    isShowDialog: false,
    isArr: null,
    name: '',
    currentCategory: 0,
    currentImg: 0,
    move: '',
    dirId:null,
	moveDirId:null,
    count: 0,
    type: 1,
    total: 0,
	loading: false,
	param: {
		search: '',
		pageNum: 1,
		pageSize: 30,
	},
    informationList: [] as Array<any>,
    setList: new Set<string>(),
    conutData: [] as Array<any>,
    treeData: [] as Array<Tree>,
    srcList: null as Array<string> | null,
    previewIndex: 0,
    
}) 
// const sortArr = ref<Array<number>>(new Array(state.informationList.length).fill(0))
const props = withDefaults(defineProps<{ 
    modelValue: boolean, 
}>(), {
    modelValue: false
})
// const srcList = computed(() => {
//     return state.informationList.map(ele => ele.src)
// })

const uploadImageVisibel = ref(false)
const categoryVisibel = ref(false)
const AddCategoryTreeNode = ref()
const uploadImageNode = ref()

// 添加分类
const addCategory = () => {
	addDirTreeRef.value.openDialog('add');
}


const toggleCategory = async (index: number) => {
	state.currentCategory = index
}

const confirmImg = async () => {
	if(state.setList.size === 0) {
        return ElMessage({
            message: '请选择图片',
            type: 'warning',
        })
    }else{
        emit('selectFun', [...state.setList],[...state.conutData]);
        state.isShowDialog = false;
    }
}


// 获取分类下文件列表
const getFileList = async () => {
	state.loading = true;
	let search = { group: [state.dirId,"="],fileName:[state.keyword,"="] }
	let params = {
		page:state.param.pageNum,
		list_rows:state.param.pageSize,
		search:JSON.stringify(search),
	}
	const { results } = await fileList(params);
	state.informationList = results.records;
	state.loading = false;
	state.total = results.total;
	state.loading = false;
}

// 获取分类列表
const getDirList = async () => {
	state.loading = true;//不用传参， 请求得入参在上面都定义了 param这里吗？
	const { results } = await dirList();
	state.treeData = results
	state.loading = false;
	if(results.length > 0){
		state.dirId = results[0].group
		getFileList();
	}
}
// 删除文件
const deleteFile = async (item: any, index: number) => {
	ElMessageBox.confirm( '确定删除该文件 ?','提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}
	) .then( async() => {
		const { method } = await fileDelete(item.id);
		if(method == 'success'){
			state.informationList.splice(index, 1);
			return ElMessage({
				type: 'success',
				message: '删除成功',
			})
		}
	})
}



const rename = (item: any, index: number) => {
	item.edit = true;
	// console.log(inputXs.value[index])
}

// 文件查看
const lookFile = async (item: any, index: number) => {
	if(item.fileType == 1){
		xgPlayVideoRef.value.openDialog(item.videoCover)
	}else{
		state.srcList = state.informationList.map(e => e.url)
		// state.srcList = state.informationList.filter(obj => obj.fileType == 0).map(e => e.url)
		ViewerApi({
			options: {
				initialViewIndex: index
			},
			images: state.srcList 
		});
	}
}

// 打开弹窗
const openDialog = (isArr:Number) => {
    state.isArr = isArr;
    getDirList()
    // 清空选中项
    state.setList.clear()
	state.isShowDialog = true;
};

const closeDialog = () => {
    state.isShowDialog = false;
}

// 文件选择
const selectImg = (i: any) => {
    if(state.setList.has(i.url)) {
        state.setList.delete(i.url)
		let x = state.conutData.findIndex(obj => obj.id === i.id)
		state.conutData.splice(x,1)
        state.count --
    } else {
		// 选中得文件对象
		state.conutData.push(i);
		// 选中得文件地址
        state.setList.add(i.url);
        state.count ++
    }
    if(state.setList.size === 0) {
		state.conutData = [] as Array<any>;
        state.count = 0
    }
};


const uploadImg = async () => uploadImageVisibel.value = true;

const pageNation = reactive({
    pageNum: 1,
    pageSize: 20,
    total: 0
})

const deleteHandle = (row: any ) => {
	ElMessageBox.confirm(
    '确定删除选中的图片 ?',
    '提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}
	)
	.then(() => {
		 
	})
	.catch(() => {
		 
    })
}

const handleCommand = (e: 'a' | 'e' | 'd', data: Tree) => {
    if(e === 'a') {
        // const newChild = { id: Date.now(), label: 'testtest', children: [], pid: data.id }
        // if (!data.children) {
        //     data.children = []
        // }
        // data.children.push(newChild)
        // state.treeData = [...state.treeData]
        categoryVisibel.value = true
    }
    if(e === 'e') {
        categoryVisibel.value = true
        AddCategoryTreeNode.value.setInitData(666, [3, 99])
    }
    if(e === 'd') {
        ElMessageBox.confirm(
        '确定删除该分类 ?',
        '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            
        })
        .catch(() => {
            
        })
    }
    console.log(e, data);
    
}

const confirmCategory = (obj: {name: string, id: Array<number>}) => {
    console.log(obj);
}

const oprationHandle = (item: any, index: number, type: 'd' | 'r' | 'p') => {
    if(type === 'd') {
        ElMessageBox.confirm(
        '确定删除该图片 ?',
        '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            
        })
        .catch(() => {
            
        })
    }
    if(type === 'r') {
        item.edit = true
    }

    if(type === 'p') {
        state.srcList = state.informationList.map(e => e.src)
        ViewerApi({
            options: {
                initialViewIndex: index
            },
            images: state.srcList 
        });
    }
}
const editBlur = (event: any, item: any, index: number) => {
    state.informationList[index].edit = false
}

const moveToHandle = (event: any) => {
    console.log(event);
    
}
// 分类切换
const changeDir = (type:any) => {
	if(state.dirId != type){
		state.dirId = type;
		getFileList();
	}
}


// 分页点击 条数
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getFileList();
}; 
// 分页点击
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getFileList();
};

// 图片上传
const uploadImgFun = () => {
	uploadImageRef.value.openDialog();
}
// 上传视频
const uploadVideoFun = () => {
	uploadVideoRef.value.openDialog();
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<template>
    <main> 
        <el-dialog v-model="state.isShowDialog" append-to-body title="上传图片" center @close="closeDialog" width="1280">
            <section class="selector-img-content">
                <section class="left-tree-wrapper"  style="display: flex;flex-direction: column;height: inherit;">
                    <section class="flex-c add-category font16" @click="addCategory">
                        <el-image style="width: 22px; height: 22px;" :src="folderAdd"  />
                        &nbsp;<span>添加分类</span>
                    </section>
                    <section>
                        <el-tree :data="state.treeData" node-key="id" highlight-current="true">
                            <template #default="{ data }">
                                <section class="dirItem font16 flex-c" :class="{isActive: state.dirId == data.group}" @click="changeDir(data.group)"
                                    style="justify-content: space-between; flex: 1;">
                                    <section class="flex-c">
                                        <el-image style="width: 22px; height: 22px;" :src="folder"  />
                                        &nbsp;&nbsp;{{ data.name }}
                                    </section>
                                    <el-dropdown v-if="data.group != 'default'" @command="handleCommand($event, data )">
                                        <span class="el-dropdown-link">
                                            <el-icon>
                                                <ele-MoreFilled />
                                            </el-icon>
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="edit">分类编辑</el-dropdown-item>
                                                <el-dropdown-item command="del">分类删除</el-dropdown-item>
                                                <el-dropdown-item command="delAll">删除所有</el-dropdown-item> 
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown> 
                                </section>
                            </template>
                        </el-tree>
                    </section>
                </section>
                
                <section class="right-material-content" style="flex-direction: column;flex: 1;height: inherit;">
                    <section style="display: flex;flex-direction: column;flex: 1;height: inherit;">
                        <section class="right-material-opration mb15 flex-c">
                            <section>
                                <el-button type="primary" @click="uploadImgFun()">上传图片</el-button>
                                <el-button type="primary" @click="uploadVideoFun()">上传视频</el-button>
                                <el-button type="danger" @click="batchDelete">删除图片</el-button>
                                <el-button type="primary" :disabled="state.setList.size === 0" @click="confirmImg">使用选中图片</el-button>
                                <el-select class="ml10" v-model="state.moveDirId" placeholder="图片移至" @change="handleChange">
                                    <el-option v-for="item in state.treeData" :key="item.group" :label="item.name" :value="item.group" />
                                </el-select>
                            </section>
                            <section class="flex-c">
                                <el-input class="width220" v-model="state.keyword" placeholder="输入图片名称搜索" @change="getFileList()"> </el-input>&emsp;
                            </section>
                        </section>
                        <section class="goods-img-list-grid" style="flex: 1;overflow: hidden;overflow-y:auto">
                            <section class="goods-img-list" v-if="state.informationList.length != 0">
                                <section class="goods-img-item mr12 mb12" v-for="(i, index) of state.informationList" :key="index">
                                    <section style="position: relative;" @click.prevent.stop="selectImg(i)"> 
                                        <el-image fit="contain" :src="i.url" :class="['goods-img', state.setList.has(i.url) ? 'active-img' : '']" />
                                        <span v-if="i.fileType == 1" style="width:128px;height:128px;position:absolute; 
                                            top:0;right:0;bottom:0;left:0; display:flex;align-items:center;justify-content:center;">
                                            <el-icon class="font36" style="color:#fff;background-color: rgba(0, 0, 0, 0.8);width:48px;height:48px;border-radius:50%;">
                                                <ele-CaretRight />
                                            </el-icon>
                                        </span>
                                    </section>
                                    <p class="goods-img-name font15">
                                        <el-input ref="inputXs" v-if="i.edit" v-model="i.filename" clearable @blur="editBlur($event, i, index)" class="font14" style="width: 128px;height:26px"></el-input>
                                        <span v-else>{{ i.filename }}</span>
                                    </p> 
                                    <section class="opration-wrapper flex-c font14">
                                        <span @click="deleteFile(i, index)">删除</span>
                                        <span @click="rename(i,index)">重命名</span>
                                        <span @click="lookFile(i, index)">查看</span>
                                    </section>
                                </section>
                            </section>
                            <section v-else style="display: flex;flex: 1;height: -webkit-fill-available; justify-content: center;align-items: center">
                                <el-empty description="暂无数据" />
                            </section>
                        </section>
                        <el-row justify="end">
                            <el-col :span="24" class="flex-end-center">
                                <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
                                    class="mt15" :page-sizes="[10, 20, 30,40]"
                                    v-model:current-page="state.param.pageNum" background v-model:page-size="state.param.pageSize"
                                    layout="total, sizes, prev, pager, next, jumper" :total="state.total">
                                </el-pagination>
                            </el-col>
                        </el-row>
                    </section>
                </section>
            </section> 
        </el-dialog>
        <xgPlayVideo ref="xgPlayVideoRef" />
		<AddDirTree ref="addDirTreeRef" @refresh="getDirList()" />
		<UploadImage ref="uploadImageRef" @refresh="getDirList()" />
		<UploadVideo ref="uploadVideoRef" @refresh="getDirList()" />
    </main>
</template>

<style lang='scss' scoped>
:deep() {
    .el-tree-node__content {
        height: auto !important;
    } 
}
.flex-c {
    display: flex;
    align-items: center;
}
.add-category{
	padding: 10px 5px;
	cursor: pointer;
}
    .selector-img-content{
        display: flex;
        height: 70vh;
        align-items: flex-start;
        .left-tree-wrapper{
            width: 200px;
            border-right: 1px solid #ededed;
            .dirItem{
                display: flex;
                align-items: center;
                padding:5px 15px;
            }
            .isActive{
                border-right: 2px solid var(--el-color-primary) !important;
                background-color:var(--el-color-primary-light-9);
            }
            :deep(.el-tree-node__content){
                padding: 0;
            }
        }

        .right-material-content{
		flex: 1;
		padding-left: 15px;
		.right-material-opration{
			justify-content: space-between;
			
		}
		
	}
	.goods-img-list-grid{
		.goods-img-item{ 
			.img-index{
				position: absolute;
				bottom: 12px;
				right: 12px;
				width: 20px;
				height: 20px;
				font-size: 13px;
				color: #fff;
				background-color: #217ef7;
				text-align: center;
				line-height: 20px;
				border-radius: 50%;
			}
			&:hover span {
				display: block;
			}
            }
            .goods-img-list{
                display: flex;
                flex-wrap: wrap;
            }
            .goods-img-name{
                width: 128px;
                text-align: center;
                overflow:hidden;
                text-overflow:ellipsis;
                white-space:nowrap;
				span{
					padding:0 10px;
				}
            }
            .goods-img{
                width: 128px;
                height: 128px; 
                object-fit: cover; 
                border-radius: 6px;
                border: 2px solid #ffffff;
                cursor: pointer;
                padding: 4px;
                border: 1px solid #fff;
                &:hover {
                    border: 1px solid #409EFF;
                }
            }
            .active-img {
                border: 1px solid #409EFF;
            }
        }
        .opration-wrapper {
            font-size: 12px; 
            color: #409EFF;
            text-align: center;
            height: 20px;
            justify-content: space-between;
            margin: 0 5px;
            
            span{
                cursor: pointer;
                display: none;
            } 
		}
	
	:deep(.el-tree-node__expand-icon.is-leaf){
		display: none;
	}
    }
</style>